/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import entities.Feriados;
import entities.Logs;
import entities.RopaBlanca;
import entities.Usuarios;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Query;
import javax.persistence.RollbackException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import logica.ExcelJTableExporter;

/**
 *
 * @author Smuggler
 */
public class AltaRopaBlanca extends JPanel {

    private Logs logs;
    private RopaBlanca r;
    private List<RopaBlanca> ropas = new ArrayList<RopaBlanca>();
    boolean editando = false;
    private Usuarios usuario;
    public static JFrame frame;

    public AltaRopaBlanca(Usuarios usuario) {
        initComponents();
        limpiarBotones();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
        this.usuario = usuario;
    }

    public JFrame getFrame() {
        return frame;
    }

    private Integer getIDRopaBlanca(String tipoRopa, String tamaño) {
        Query queryIDRopaBlanca;
        RopaBlanca ropa;
        queryIDRopaBlanca = entityManager.createNamedQuery("RopaBlanca.findByTipoRopaTamaño");
        queryIDRopaBlanca.setParameter("tipoRopa", tipoRopa);
        queryIDRopaBlanca.setParameter("tamaño", tamaño);
        ropa = (RopaBlanca) queryIDRopaBlanca.getSingleResult();
        return ropa.getIdRopa();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SIAATPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT r FROM RopaBlanca r ORDER BY r.tipoRopa ASC");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        ropaBlancaQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT r FROM RopaBlanca r");
        ropaBlancaList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : ropaBlancaQuery.getResultList();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        tipoRopaLabel = new javax.swing.JLabel();
        tamañoLabel = new javax.swing.JLabel();
        descripciónLabel = new javax.swing.JLabel();
        cantidadLabel = new javax.swing.JLabel();
        guardarButton = new javax.swing.JButton();
        nuevoButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        descripcionTextArea = new javax.swing.JTextArea();
        cantidadSpinner = new javax.swing.JSpinner();
        tamañoComboBox = new javax.swing.JComboBox();
        tipoRopaComboBox = new javax.swing.JComboBox();
        cancelarButton = new javax.swing.JButton();
        borrarButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        ayudaLabel = new javax.swing.JLabel();
        exportarExcelButton = new javax.swing.JButton();

        FormListener formListener = new FormListener();

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${tipoRopa}"));
        columnBinding.setColumnName("Tipo Ropa");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${tamaño}"));
        columnBinding.setColumnName("Tamaño");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cantidad}"));
        columnBinding.setColumnName("Cantidad");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${descripción}"));
        columnBinding.setColumnName("Descripción");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterTable.addMouseListener(formListener);
        masterScrollPane.setViewportView(masterTable);
        masterTable.getColumnModel().getColumn(0).setResizable(false);
        masterTable.getColumnModel().getColumn(1).setResizable(false);
        masterTable.getColumnModel().getColumn(2).setResizable(false);
        masterTable.getColumnModel().getColumn(3).setResizable(false);

        tipoRopaLabel.setText("Tipo Ropa:");

        tamañoLabel.setText("Tamaño:");

        descripciónLabel.setText("Descripción:");

        cantidadLabel.setText("Cantidad:");

        guardarButton.setBackground(new java.awt.Color(1, 154, 210));
        guardarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        guardarButton.setForeground(new java.awt.Color(255, 255, 255));
        guardarButton.setText("Guardar");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), guardarButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        guardarButton.addActionListener(formListener);

        nuevoButton.setBackground(new java.awt.Color(1, 154, 210));
        nuevoButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        nuevoButton.setForeground(new java.awt.Color(255, 255, 255));
        nuevoButton.setText("Nuevo");
        nuevoButton.addActionListener(formListener);

        descripcionTextArea.setColumns(20);
        descripcionTextArea.setRows(5);
        descripcionTextArea.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.descripción}"), descripcionTextArea, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jScrollPane1.setViewportView(descripcionTextArea);

        cantidadSpinner.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1)));
        cantidadSpinner.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.cantidad}"), cantidadSpinner, org.jdesktop.beansbinding.BeanProperty.create("value"));
        bindingGroup.addBinding(binding);

        tamañoComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "QUEEN", "KING", "TWEEN", "1½ PLAZAS", "2½ PLAZAS", "GRANDE", "MEDIANO", "CHICO", "OTRO" }));
        tamañoComboBox.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.tamaño}"), tamañoComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        tipoRopaComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "SABANA AJUSTABLE", "SABANAS PORTICO", "SÁBANA", "CUBRECAMA", "COVER", "ACOLCHADO", "EDREDON", "CUBREEDREDON", "MANTA", "FRAZADA", "ALMOHADA", "CUBRESOMIER", "FUNDA", "PROTECTOR DE COLCHON", "TOALLA", "TOALLON" }));
        tipoRopaComboBox.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.tipoRopa}"), tipoRopaComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        cancelarButton.setBackground(new java.awt.Color(1, 154, 210));
        cancelarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        cancelarButton.setForeground(new java.awt.Color(255, 255, 255));
        cancelarButton.setText("Cancelar");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), cancelarButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        cancelarButton.addActionListener(formListener);

        borrarButton.setBackground(new java.awt.Color(1, 154, 210));
        borrarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        borrarButton.setForeground(new java.awt.Color(255, 255, 255));
        borrarButton.setText("Borrar");
        borrarButton.setEnabled(false);
        borrarButton.addActionListener(formListener);

        ayudaLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help.png"))); // NOI18N
        ayudaLabel.addMouseListener(formListener);

        exportarExcelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/xls.png"))); // NOI18N
        exportarExcelButton.setText("Exportar");
        exportarExcelButton.addActionListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(ayudaLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(exportarExcelButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(nuevoButton)
                        .addGap(14, 14, 14)
                        .addComponent(borrarButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cancelarButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(guardarButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(masterScrollPane)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(tipoRopaLabel)
                                    .addComponent(descripciónLabel))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(tipoRopaComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(tamañoLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(tamañoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(cantidadLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(cantidadSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 508, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(1, 1, 1)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {guardarButton, nuevoButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tipoRopaLabel)
                    .addComponent(tamañoLabel)
                    .addComponent(tamañoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tipoRopaComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cantidadLabel)
                    .addComponent(cantidadSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(descripciónLabel)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(guardarButton)
                            .addComponent(nuevoButton)
                            .addComponent(cancelarButton)
                            .addComponent(borrarButton))
                        .addContainerGap(24, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(ayudaLabel))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(exportarExcelButton)))
                        .addGap(7, 7, 7))))
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.MouseListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == guardarButton) {
                AltaRopaBlanca.this.guardarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == nuevoButton) {
                AltaRopaBlanca.this.nuevoButtonActionPerformed(evt);
            }
            else if (evt.getSource() == cancelarButton) {
                AltaRopaBlanca.this.cancelarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == borrarButton) {
                AltaRopaBlanca.this.borrarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == exportarExcelButton) {
                AltaRopaBlanca.this.exportarExcelButtonActionPerformed(evt);
            }
        }

        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == masterTable) {
                AltaRopaBlanca.this.masterTableMouseClicked(evt);
            }
        }

        public void mouseEntered(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == ayudaLabel) {
                AltaRopaBlanca.this.ayudaLabelMouseEntered(evt);
            }
        }

        public void mouseExited(java.awt.event.MouseEvent evt) {
        }

        public void mousePressed(java.awt.event.MouseEvent evt) {
        }

        public void mouseReleased(java.awt.event.MouseEvent evt) {
        }
    }// </editor-fold>//GEN-END:initComponents

    private void habilitarBotones(boolean estado) {
        tipoRopaComboBox.setEnabled(estado);
        tamañoComboBox.setEnabled(estado);
        cantidadSpinner.setEnabled(estado);
        descripcionTextArea.setEnabled(estado);
        nuevoButton.setEnabled(!estado);
        masterTable.setEnabled(!estado);
        borrarButton.setEnabled(estado);
    }

    private void refrescar() {
        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
        habilitarBotones(false);
        limpiarBotones();
        editando = false;
    }

    private void limpiarBotones() {
        descripcionTextArea.setText("");
        cantidadSpinner.setValue(0);
        tipoRopaComboBox.setSelectedIndex(-1);
        tamañoComboBox.setSelectedIndex(-1);
    }

    private void cargarRopaBlanca() {
        ropas = entityManager.createNamedQuery("RopaBlanca.findAll").getResultList();
    }

    private void nuevoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed
        habilitarBotones(true);
        cargarRopaBlanca();
        borrarButton.setEnabled(false);
        r = new entities.RopaBlanca();
        logs = new Logs();
        logs.setUsuario(usuario);
        entityManager.persist(r);
        list.add(r);
        int row = list.size() - 1;
        masterTable.setRowSelectionInterval(row, row);
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
        editando = false;
    }//GEN-LAST:event_nuevoButtonActionPerformed
    private boolean existeRopaBlanca() {
        int cont = 0;

        for (RopaBlanca ropa : list) {
            if (ropa.getTipoRopa().equalsIgnoreCase(tipoRopaComboBox.getSelectedItem().toString())
                    && ropa.getTamaño().equalsIgnoreCase(tamañoComboBox.getSelectedItem().toString())) {
                cont++;
            }
        }

        if (cont < 2) {
            return false;
        }
        return true;
    }
    private void guardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarButtonActionPerformed
        if ((tipoRopaComboBox.getSelectedIndex() == -1) || (tamañoComboBox.getSelectedIndex() == -1)) {
            JOptionPane.showMessageDialog(this, "El campo Tipo de Ropa y Tamaño no pueden quedar nulos", "Atención", JOptionPane.ERROR_MESSAGE, null);
        } else if (existeRopaBlanca()) {
            JOptionPane.showMessageDialog(this, "Ya existe la ropa blanca que desea ingresar, "
                    + "TIPO y TAMAÑO duplicado", "Atención", WIDTH, null);
            tipoRopaComboBox.requestFocus();
        } else {
            try {
                logs = new Logs();
                logs.setUsuario(usuario);
                if (r.getIdRopa() == null) {
                    entityManager.getTransaction().commit();
                    entityManager.getTransaction().begin();
                    Integer idRopa = getIDRopaBlanca(r.getTipoRopa(), r.getTamaño());
                    logs.setearObservaciones("Alta", "RopaBlanca", idRopa, "AltaRopaBlanca");
                } else {
                    logs.setearObservaciones("Modificación", "RopaBlanca", r.getIdRopa(), "AltaRopaBlanca");
                }
                entityManager.persist(logs);
                entityManager.getTransaction().commit();
                entityManager.getTransaction().begin();
            } catch (RollbackException rex) {
                rex.printStackTrace();
                entityManager.getTransaction().begin();
                List<entities.RopaBlanca> merged = new ArrayList<entities.RopaBlanca>(list.size());
                for (entities.RopaBlanca r : list) {
                    merged.add(entityManager.merge(r));
                }
                list.clear();
                list.addAll(merged);
            }
            habilitarBotones(false);
            refrescar();
        }
    }//GEN-LAST:event_guardarButtonActionPerformed

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        refrescar(); // TODO add your handling code here:
    }//GEN-LAST:event_cancelarButtonActionPerformed

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        habilitarBotones(true);
        r = list.get(masterTable.getSelectedRow());
        editando = true;
    }//GEN-LAST:event_masterTableMouseClicked

    private void borrarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_borrarButtonActionPerformed
        int respuesta = JOptionPane.showConfirmDialog(null, "Desea confirmar el borrado de la Ropa Blanca?", "Borrado de Ropa Blanca", JOptionPane.YES_NO_OPTION);
        if (respuesta == JOptionPane.YES_OPTION) {
            int[] selected = masterTable.getSelectedRows();
            List<entities.RopaBlanca> toRemove = new ArrayList<entities.RopaBlanca>(selected.length);

            for (int idx = 0; idx < selected.length; idx++) {
                entities.RopaBlanca r = list.get(masterTable.convertRowIndexToModel(selected[idx]));
                toRemove.add(r);
                logs = new Logs();
                logs.setUsuario(usuario);
                logs.setearObservaciones("Borrado", "RopaBlanca", r.getIdRopa(), "AltaRopaBlanca");
                entityManager.persist(logs);
                entityManager.remove(r);
            }
            list.removeAll(toRemove);
            entityManager.getTransaction().commit();
            entityManager.getTransaction().begin();
            //guardarButtonActionPerformed(null);
            cancelarButtonActionPerformed(null);
        }
    }//GEN-LAST:event_borrarButtonActionPerformed

    private void ayudaLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ayudaLabelMouseEntered
        ayudaLabel.setToolTipText("En esta pantalla usted podra agregar,\n editar y eliminar ropa blanca");
    }//GEN-LAST:event_ayudaLabelMouseEntered

    private void exportarExcelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportarExcelButtonActionPerformed
        new ExcelJTableExporter(masterTable, "Ropa Blanca").export();
    }//GEN-LAST:event_exportarExcelButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel ayudaLabel;
    private javax.swing.JButton borrarButton;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JLabel cantidadLabel;
    private javax.swing.JSpinner cantidadSpinner;
    private javax.swing.JTextArea descripcionTextArea;
    private javax.swing.JLabel descripciónLabel;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JButton exportarExcelButton;
    private javax.swing.JButton guardarButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private java.util.List<entities.RopaBlanca> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JButton nuevoButton;
    private javax.persistence.Query query;
    private java.util.List<entities.RopaBlanca> ropaBlancaList;
    private javax.persistence.Query ropaBlancaQuery;
    private javax.swing.JComboBox tamañoComboBox;
    private javax.swing.JLabel tamañoLabel;
    private javax.swing.JComboBox tipoRopaComboBox;
    private javax.swing.JLabel tipoRopaLabel;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public static void main(Usuarios user) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AltaRopaBlanca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AltaRopaBlanca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AltaRopaBlanca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AltaRopaBlanca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        final Usuarios usuario = user;
        /*
         * Create and display the form
         */
        AltaRopaBlanca.frame = new JFrame();
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                frame.setContentPane(new AltaRopaBlanca(usuario));
                frame.pack();
                frame.setVisible(true);
                frame.setTitle("Inventario   -   Ropa Blanca   -   Sistema Integrado de Administración de Alquileres Turísticos  ");
                frame.setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage());
                frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        if (frame != null) {
                            frame.setVisible(false);
                        }
                        frame = null;
                    }
                });
            }
        });
    }
}
